var keystone = require('keystone');
var Promise = require("bluebird");

exports.user_list = function (req, res) {

    const locals = res.locals;
    locals.data = {};
    const page = req.query.page ? req.query.page - 1 : 0;
    const order = req.query.order && req.query.order == 'asc' ? '' : '-';

    new Promise((resolve, reject) => {

        keystone.list('UserProfile').model
            .findOne({ user: req.query.current_user })
            .exec((err, userProfile) => {
                if (err) {
                    return reject(err);
                }
                locals.data.permission = userProfile.permission
                return resolve(userProfile.permission);
            })
    })
        .then((permission) => {
            return keystone.list('UserProfile').model
                .find({ permission: { $lt: permission } })
                .populate({
                    path: 'user',

                })
                .sort(order + 'permission')
                .skip(page * 15).limit(15)
                .exec((err, users) => {
                    if (err) {
                        return new Promise((resolve, reject) => { reject(err) });
                    }
                    return users

                })
        })
        .then((users) => {
            keystone.list('UserProfile').model
                .find({ permission: { $lt: locals.data.permission } })
                .count()
                .exec((err, user_count) => {
                    if (err) {
                        return new Promise((resolve, reject) => { reject(err) });
                    }
                    res.json({
                        users: users,
                        user_count: user_count
                    });
                })
        })
        .catch((err) => {
            throw err;
        })


}
